﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FxWinSuper.Plugin.Data;
using FxWinSuper.Plugin.Extension;
using Newtonsoft.Json;
using WinSupperUpdateService.Model;

namespace WinSupperUpdateService.Store
{
	internal class FileSystemPluginStore : IPluginStore
	{
		public static readonly string PluginRootDirectory = @"C:\Users\Administrator\Documents\fxwinsupper\localfiles";

		public static readonly string PluginMetaFile = Path.Combine(PluginRootDirectory, "meta.json");

		private PluginMeta _pluginMeta;

		internal FileSystemPluginStore()
		{
			_pluginMeta = JsonConvert.DeserializeObject<PluginMeta>(File.ReadAllText(PluginMetaFile));
		}

		public Task<List<RemotePluginEntity>> GetAllPlugins()
		{
			List<RemotePluginEntity> remotePluginEntities = new List<RemotePluginEntity>();
			remotePluginEntities.AddRange(_pluginMeta.Plugins);
			return Task.FromResult(remotePluginEntities);
		}

		public Task<List<RemotePluginEntity>> SearchPlugin(string pluginName)
		{
			List<RemotePluginEntity> remotePluginEntities = new List<RemotePluginEntity>();
			_pluginMeta.Plugins.ForEach(plugin =>
			{
				if (plugin.PluginName.ToLower().Contains(pluginName.ToLower()))
				{
					remotePluginEntities.Add(plugin);
				}
			});
			return Task.FromResult(remotePluginEntities);
		}

		public Task<bool> DownloadPlugin(string pluginName, string targetFilepath, Action<int> ProgressCallback = null)
		{
			if (File.Exists(targetFilepath))
			{
				File.Delete(targetFilepath);
			}

			PluginEntity pluginEntity = _pluginMeta.Plugins.FirstOrDefault(plugin => plugin.PluginName == pluginName);
			if (pluginEntity == null)
			{
				throw new Exception("未获取到插件信息");
			}

			File.Copy(Path.Combine(PluginRootDirectory, pluginEntity.PackagePath), targetFilepath);
			// 文件系统直接复制，不校验包
			ProgressCallback?.Invoke(100);
			return Task.FromResult(true);
		}

		public Task<RemotePluginEntity> GetPluginInfo(string pluginName)
		{
			return  Task.FromResult(_pluginMeta.Plugins.FirstOrDefault(plugin => plugin.PluginName == pluginName) as RemotePluginEntity);
		}
	}
}
